import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_xupdate/flutter_xupdate.dart';
import 'package:url_launcher/url_launcher.dart';

class UpgradePage extends StatelessWidget {
  const UpgradePage({super.key});

  @override
  Widget build(BuildContext context) {
    if (Platform.isAndroid) {
      checkUpdateDefault();
    } else if (Platform.isIOS) {
      // 在父组件创建完成之后，再创建小组件。
      WidgetsBinding.instance.addPostFrameCallback((_) {
        showIOSDialog(context);
      });
    }
    return Scaffold(
      appBar: AppBar(title: const Text('版本更新')),
      body: const Text('版本更新页面'),
    );
  }
}

///初始化
void initXUpdate() {
  if (Platform.isAndroid) {
    FlutterXUpdate.init(
      ///是否输出日志
      debug: true,

      ///是否使用post请求
      isPost: false,

      ///post请求是否是上传json
      isPostJson: false,

      ///请求响应超时时间
      timeout: 25000,

      ///是否开启自动模式
      isWifiOnly: false,

      ///是否开启自动模式
      isAutoMode: false,

      ///需要设置的公共参数
      supportSilentInstall: false,

      ///在下载过程中，如果点击了取消的话，是否弹出切换下载方式的重试提示弹窗
      enableRetry: false,
    ).then((value) {
      print("初始化成功: $value");
    }).catchError((error) {
      print(error);
    });

    FlutterXUpdate.setErrorHandler(onUpdateError: (message) async {});
  } else {
    // updateMessage("ios暂不支持XUpdate更新");
  }
}

final String _updateUrl1 = 'https://gitee.com/xuexiangjys/XUpdate/raw/master/jsonapi/update_test.json';
// 强制更新
final String _updateUrl2 = 'https://gitee.com/xuexiangjys/XUpdate/raw/master/jsonapi/update_forced.json';
final String _updateUrl3 = 'https://gitee.com/xuexiangjys/XUpdate/raw/master/jsonapi/update_custom.json';

///默认App更新
void checkUpdateDefault() {
  FlutterXUpdate.checkUpdate(url: _updateUrl1);
}

// 跳转 AppStore 更新 iOSUrl APP 在 AppStore 的链接
Future<void> showIOSDialog(context) async {
  showDialog(
    context: context,
    barrierDismissible: false,
    builder: (context) {
      return Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            padding: const EdgeInsets.fromLTRB(40.0, 0, 40.0, 0),
            child: Image(
              width: MediaQuery.of(context).size.width,
              image: const AssetImage("images/bg_update_top.png"),
              fit: BoxFit.fill,
            ),
          ),
          Container(
            width: MediaQuery.of(context).size.width,
            margin: const EdgeInsets.fromLTRB(40.0, 0, 40.0, 0),
            decoration: const BoxDecoration(
              color: Color(0xffffffff),
              borderRadius: BorderRadius.only(
                bottomLeft: Radius.circular(10),
                bottomRight: Radius.circular(10),
              ),
            ),
            child: Container(
              padding: const EdgeInsets.fromLTRB(20.0, 0, 20.0, 0.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Padding(
                    padding: EdgeInsets.only(bottom: 8.0, top: 10.0),
                    child: Text(
                      '是否升级到1.2.0版本',
                      style: TextStyle(
                        fontSize: 14.0,
                        color: Color(0xff555555),
                        decoration: TextDecoration.none,
                      ),
                      textAlign: TextAlign.left,
                    ),
                  ),
                  const Padding(
                    padding: EdgeInsets.only(bottom: 15.0),
                    child: Text(
                      '新版本大小： 12.7MB',
                      style: TextStyle(
                        fontSize: 13.0,
                        color: Color(0xff777777),
                        decoration: TextDecoration.none,
                      ),
                      textAlign: TextAlign.left,
                    ),
                  ),
                  SizedBox(
                    height: 110.0,
                    child: ListView(
                      itemExtent: null,
                      shrinkWrap: true,
                      children: const [
                        Padding(
                          padding: EdgeInsets.only(bottom: 6.0),
                          child: Text(
                            '1、优化页面及首页加载速度',
                            style: TextStyle(
                              fontSize: 13.0,
                              color: Color(0xff777777),
                              decoration: TextDecoration.none,
                            ),
                            textAlign: TextAlign.left,
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(bottom: 6.0),
                          child: Text(
                            '2、提高蓝牙开门响应时间',
                            style: TextStyle(
                              fontSize: 13.0,
                              color: Color(0xff777777),
                              decoration: TextDecoration.none,
                            ),
                            textAlign: TextAlign.left,
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(bottom: 6.0),
                          child: Text(
                            '3、降低蓝牙扫码耗电',
                            style: TextStyle(
                              fontSize: 13.0,
                              color: Color(0xff777777),
                              decoration: TextDecoration.none,
                            ),
                            textAlign: TextAlign.left,
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(bottom: 6.0),
                          child: Text(
                            '4、增加版本更新提示',
                            style: TextStyle(
                              fontSize: 13.0,
                              color: Color(0xff777777),
                              decoration: TextDecoration.none,
                            ),
                            textAlign: TextAlign.left,
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    margin: const EdgeInsets.only(bottom: 6.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        TextButton(
                          child: const Text(
                            "下次再说",
                            style: TextStyle(color: Color(0xffffbb5b), fontSize: 18.0),
                          ),
                          onPressed: () {
                            Navigator.of(context).pop();
                          }, //关闭对话框
                        ),
                        TextButton(
                          child: const Text(
                            "立即前往",
                            style: TextStyle(color: Color(0xffffbb5b), fontSize: 18.0),
                          ),
                          onPressed: () async {
                            const iOSUrl = 'https://itunes.apple.com/us/app/your-app-name/id1234567890?ls=1&mt=8';
                            try {
                              if (await launchUrl(Uri.parse(iOSUrl))) {
                                await launchUrl(Uri.parse(iOSUrl));
                              }
                            } catch (e) {
                              print("err: $e");
                            }
                          }, //关闭对话框
                        ),
                      ],
                    ),
                  )
                ],
              ),
            ),
          ),
        ],
      );
    },
  );
}
